<template>
  <view class="region-select">
    <view class="selected-text" @click="visible = true">
      {{ displayText || '请选择省市区县' }}
    </view>

    <nut-popup v-model:visible="visible" position="bottom">
      <view class="region-content">
        <view class="region-header">
          <text>请选择所在地区</text>
          <nut-icon name="close" @click="visible = false" />
        </view>

        <view class="tabs">
          <view
            v-for="(tab, index) in tabs"
            :key="index"
            class="tab-item"
            :class="{ active: currentLevel === tab.level }"
            @click="onTabClick(tab)"
          >
            {{ tab.name || '请选择' }}
          </view>
        </view>

        <scroll-view class="options" scroll-y>
          <view
            v-for="item in currentOptions"
            :key="item.code"
            class="option-item"
            :class="{ active: isSelected(item) }"
            @click="onSelect(item)"
          >
            {{ item.name }}
          </view>
        </scroll-view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
//新封装的省市县
import { ref, watch, onMounted } from 'vue'
import { useReturnStore } from '@/stores/modules/returnStore'
import { getPostList } from '@/services/system'

const store = useReturnStore()

const props = defineProps({
  provinceId: {
    type: String,
    default: '',
  },
  cityId: {
    type: String,
    default: '',
  },
  districtId: {
    type: String,
    default: '',
  },
  streetId: {
    type: String,
    default: '',
  },
})

const emit = defineEmits([
  'update:provinceId',
  'update:cityId',
  'update:districtId',
  'update:streetId',
  'change',
])

// 数据
const visible = ref(false)
const currentLevel = ref(1)
const currentOptions = ref<any[]>([])
const displayText = ref('')

// 选中的数据
const selectedData = ref<Record<number, any>>({})
const tabs = ref<Array<{ level: number; name: string }>>([{ level: 1, name: '' }])

// 从store获取地址字典
const getRegionDict = () => {
  return store.getRegionDictory() || []
}

// 加载地址字典
const loadRegionDict = async () => {
  try {
    // 先从store获取
    let dict = getRegionDict()

    // 如果store中没有，从服务器获取
    if (!dict || !dict.length) {
      uni.showLoading({ title: '' })
      const { data } = await getPostList()
      if (data?.length) {
        dict = data
        // 保存到store
        store.setRegionDict(dict)
      }
      uni.hideLoading()
    }

    return dict?.length > 0
  } catch (e) {
    console.error('加载地址字典失败', e)
    uni.showToast({
      title: '获取地址失败',
      icon: 'none',
    })
    return false
  }
}

// 获取下级地区
const getChildrenByParent = (parentId: string) => {
  const dict = getRegionDict()
  return dict.filter((item) => item.parent === parentId)
}

// 加载某一级别的数据
const loadLevelData = (parent = '0') => {
  const children = getChildrenByParent(parent)
  currentOptions.value = children
}

// 判断是否选中
const isSelected = (item: any) => {
  const selected = selectedData.value[currentLevel.value]
  return selected && selected.code === item.code
}

// 选择某一项
const onSelect = (item: any) => {
  // 保存选择
  selectedData.value[currentLevel.value] = item

  // 更新tab名称
  const tab = tabs.value.find((t) => t.level === currentLevel.value)
  if (tab) {
    tab.name = item.name
  }

  // 如果有下一级，添加下一级的tab
  const children = getChildrenByParent(item.code)
  if (children.length > 0 && currentLevel.value < 4) {
    // 移除当前级别之后的所有tab
    tabs.value = tabs.value.filter((t) => t.level <= currentLevel.value)
    // 添加下一级tab
    tabs.value.push({
      level: currentLevel.value + 1,
      name: '',
    })
    // 切换到下一级
    currentLevel.value++
    // 加载下一级数据
    loadLevelData(item.code)
  } else {
    // 没有下一级，关闭弹窗，发送结果
    visible.value = false
    emitResult()
  }
}

// 点击tab
const onTabClick = (tab: any) => {
  if (currentLevel.value === tab.level) return

  currentLevel.value = tab.level
  const selected = selectedData.value[tab.level - 1]
  loadLevelData(selected ? selected.code : '0')
}

// 发送选择结果
const emitResult = () => {
  const detail: Record<string, any> = {}
  let text = ''

  for (let i = 1; i <= 4; i++) {
    const data = selectedData.value[i]
    if (data) {
      detail[i] = {
        code: data.code,
        name: data.name,
        level: i,
      }
      text += data.name
    }
  }

  displayText.value = text

  emit('update:provinceId', detail[1]?.code || '')
  emit('update:cityId', detail[2]?.code || '')
  emit('update:districtId', detail[3]?.code || '')
  emit('update:streetId', detail[4]?.code || '')
  emit('change', detail)
}

// 初始化选中值
const initSelectedValue = async () => {
  if (!props.provinceId) return

  const dict = getRegionDict()
  if (!dict.length) return

  // 清空现有数据
  selectedData.value = {}
  tabs.value = [{ level: 1, name: '' }]

  // 初始化省
  const province = dict.find((item) => item.code === props.provinceId)
  if (province) {
    selectedData.value[1] = province
    tabs.value[0].name = province.name

    // 初始化市
    if (props.cityId) {
      const city = dict.find((item) => item.code === props.cityId)
      if (city) {
        selectedData.value[2] = city
        tabs.value.push({ level: 2, name: city.name })

        // 初始化区
        if (props.districtId) {
          const district = dict.find((item) => item.code === props.districtId)
          if (district) {
            selectedData.value[3] = district
            tabs.value.push({ level: 3, name: district.name })

            // 初始化街道
            if (props.streetId) {
              const street = dict.find((item) => item.code === props.streetId)
              if (street) {
                selectedData.value[4] = street
                tabs.value.push({ level: 4, name: street.name })
              }
            }
          }
        }
      }
    }
  }

  // 更新显示文本
  let text = ''
  Object.values(selectedData.value).forEach((item) => {
    text += item.name
  })
  displayText.value = text

  // 设置当前级别为最后一级
  currentLevel.value = tabs.value[tabs.value.length - 1].level
  loadLevelData(selectedData.value[currentLevel.value - 1]?.code || '0')
}

// 监听props变化
watch(
  [() => props.provinceId, () => props.cityId, () => props.districtId, () => props.streetId],
  async () => {
    await initSelectedValue()
  },
)

// 监听弹窗显示
watch(
  () => visible.value,
  async (val) => {
    if (val) {
      // 打开弹窗时，如果没有选择过，加载第一级数据
      if (!selectedData.value[1]) {
        currentLevel.value = 1
        loadLevelData()
      }
    }
  },
)

// 组件挂载
onMounted(async () => {
  await loadRegionDict()
  await initSelectedValue()
})
</script>

<style lang="scss" scoped>
.region-select {
  width: 100%;

  .selected-text {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    padding: 0 20rpx;

    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;

    &:empty::before {
      content: '请选择地区';
      color: #999;
    }
  }
}

.region-content {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;

  .region-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    padding: 0 30rpx;
    font-size: 32rpx;
    border-bottom: 1px solid #eee;
  }

  .tabs {
    display: flex;
    padding: 20rpx 30rpx;
    border-bottom: 1px solid #eee;

    .tab-item {
      padding: 10rpx 20rpx;
      margin-right: 20rpx;
      font-size: 28rpx;
      color: #666;

      &.active {
        color: #2979ff;
      }

      &:empty::before {
        content: '请选择';
        color: #999;
      }
    }
  }

  .options {
    height: 600rpx;
    padding: 20rpx 0;

    .option-item {
      padding: 20rpx 30rpx;
      font-size: 28rpx;

      &.active {
        color: #2979ff;
      }
    }
  }
}
</style>
